/*
 * Copyright 2020 tu.cn All right reserved. This software is the
 * confidential and proprietary information of tu.cn ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Tu.cn
 */
package com.onedec.cloud.onedexapigateway.fliter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.onedec.cloud.onedexapigateway.utils.RequestContextUtils;
import com.onedec.entity.OnedecEmp;
import lombok.SneakyThrows;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 31014
 * @date 2020/7/14 19:16
 */
@Component
public class AuthFilter extends ZuulFilter {
    private static List<String> whitelist = new ArrayList<String>();

    static {
        whitelist.add("/page/page/admin/index.html");
        whitelist.add("/admin/login");
    }

    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    public int filterOrder() {
        return FilterConstants.RIBBON_ROUTING_FILTER_ORDER - 5;
    }

    public boolean shouldFilter() {
        String requestURI = RequestContextUtils.getRequestURI();
        System.out.println(requestURI);
        final boolean b = whitelist.contains(requestURI);
        return !(b || requestURI.endsWith(".css") || requestURI.endsWith(".js") || requestURI.endsWith(".img") || requestURI.endsWith(".png"));
    }

    @SneakyThrows
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        final HttpServletRequest request = currentContext.getRequest();
        final Object emp = request.getSession().getAttribute("emp");
        final HttpServletResponse response = currentContext.getResponse();
        if (emp == null) {
            response.sendRedirect("/page/page/admin/index.html");
        }else {
            currentContext.setSendZuulResponse(true);
        }
        return null;
    }
}